package com.agilespirit.application;

import java.util.ArrayList;
import java.util.List;

import com.agilespirit.domain.Application;

public class ApplicationServiceImpl implements ApplicationService {

  private static ApplicationService instance;
  private final List<Application> list = new ArrayList<Application>();
  private Integer index = 1;

  private ApplicationServiceImpl() {
  }

  public static ApplicationService getInstance() {
    if (instance == null) {
      instance = new ApplicationServiceImpl();
    }
    return instance;
  }

  @Override
  public List<Application> find(String filter) {
    List<Application> result = new ArrayList<Application>();
    if (filter != null && !filter.isEmpty()) {
      for (Application application : list) {
        if (filter.equalsIgnoreCase(application.getName())) {
          result.add(application);
        }
      }
    }
    return list;
  }

  @Override
  public Application getById(Integer id) {
    if (id != null) {
      for (Application application : list) {
        if (application.getId().equals(id)) {
          return application;
        }
      }
    }
    return null;
  }

  @Override
  public Application saveOrUpdate(Application application) {
    if (application != null) {
      Application persisted = getById(application.getId());
      // Save
      if (persisted == null) {
        application.setId(index);
        list.add(application);
        index++;
      } else { // Update
        persisted.setName(application.getName());
        persisted.setEnvironment(application.getEnvironment());
        persisted.setPlatform(application.getPlatform());
        persisted.setCountry(application.getCountry());
        persisted.setHost(application.getHost());
        persisted.setPort(application.getPort());
        persisted.setUsername(application.getUsername());
        persisted.setPassword(application.getPassword());
      }
      return persisted;
    }
    return null;
  }

  @Override
  public boolean delete(Integer id) {
    if (id != null) {
      for (Application application : list) {
        if (application.getId().equals(id)) {
          list.remove(application);
          return true;
        }
      }
    }
    return false;
  }

}
